package com.song.rabbitmq.c_driect;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * direct 路由模式
 *      特点：Direct模式是fanout模式上的一种叠加，增加了路由RoutingKey的模式。
 */
public class Producer {

    public static void main(String[] args) {
        // 创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        // 设置连接属性
        connectionFactory.setHost("121.41.53.91");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        Connection connection = null;
        Channel channel = null;
        try {
            // 1.从连接工厂中获取连接
            connection = connectionFactory.newConnection("direct路由模式-生产者");
            // 2: 从连接中获取通道channel
            channel = connection.createChannel();
            // 准备发送消息的内容
            String message = "你好，by direct路由模式的消息！！！";
            String exchangeName = "direct-exchange";
            String routingKey1 = "qq";
            String routingKey2 = "weixin";
            String routingKey3 = "email";
            //String routingKey4 = "dingding";  除了钉钉不接收消息，路由中其他队列都接收消息

            // 3.发送消息给中间件rabbitmq-server
            // @params1: 交换机exchange
            // @params2: 队列名称/routingkey
            // @params3: 属性配置
            // @params4: 发送消息的内容
            channel.basicPublish(exchangeName, routingKey1, null, message.getBytes());
            channel.basicPublish(exchangeName, routingKey2, null, message.getBytes());
            channel.basicPublish(exchangeName, routingKey3, null, message.getBytes());

        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("发送消息出现异常...");
        } finally {
            // 释放连接关闭通道
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (connection != null  && connection.isOpen()) {
                try {
                    connection.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

}
